package com.isoftstone.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.isoftstone.pojo.Users;
import com.isoftstone.service.UserService;
import com.isoftstone.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    private UserService userService;
    private LineCaptcha lineCaptcha;

    @PostMapping("/user")
    public Result<?> insertUser(@RequestBody Users users)
    {

        return userService.insertUser(users);
    }

    //修改用户信息
    @PutMapping("/user")
    public Result<?> updateUser(@RequestBody Users users){
        return userService.updateUser(users);
    }
    //查询用户信息
//    @GetMapping("/user")
//    public Result<Users> queryUserByPhone(String phone){
//        return userService.queryUserByPhone(phone);
//    }
    //删除用户
    @DeleteMapping("/user/{id}")
    public Result<?> deleteUser(@PathVariable Integer id){
        return userService.deleteUser(id);
    }
    //查询所有用户
    @GetMapping("/user")
    public Result<?> queryAllUser(@RequestParam (defaultValue = "1") Integer currentPage,
                                  @RequestParam(defaultValue = "5") Integer pageSize){
        Page page = userService.queryAllUser(currentPage, pageSize);
        PageInfo<Object> pageInfo = new PageInfo<>(page);
        return Result.success(pageInfo);
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response){
        lineCaptcha  = CaptchaUtil.createLineCaptcha(125,45);
        lineCaptcha.setBackground(new Color(181,238,218));
        //写出数据倒流
        try{
            ServletOutputStream os = response.getOutputStream();
            lineCaptcha.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("/login")
    public Result<?> login(@RequestBody  Map<String, String> user) {
        String code = user.get("code");
//        验证码验证
        if (!lineCaptcha.verify(code)) {
            return Result.error("验证码错误");
        }
        return userService.login(user.get("phone"), user.get("password"),user.get("photo"));
    }
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        userService.exportExcel(response);
    }

    @PostMapping("/import")
    public Result<?> importExcel( MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(is);

        try{
            List<Users> list = reader.readAll(Users.class);
            list.stream().forEach(users -> userService.insertUser(users));
        }catch (Exception e){
            Result.error("导入失败");
        }
        return Result.success("导入成功");
    }
//@PostMapping("/import")
//public Result<?> importExcel(MultipartFile file) throws IOException {
//    //1.通过file对象获取输入流对象
//    InputStream is = file.getInputStream();
//    //读取流
//    ExcelReader excelReader = ExcelUtil.getReader(is);
//    List<Users> usersList = excelReader.readAll(Users.class);
//    //批处理
//    //usersList.stream().forEach(users-> userService.insertUser(users));
//    int successCount = 0;
//    int failCount = 0;
//    StringBuilder errorMsg = new StringBuilder();
//
//    for (Users users : usersList) {
//        try {
//            Result result = userService.insertUser(users);
//            if (result != null && "操作成功".equals(result.getMessage())) {
//                successCount++;
//                log.info("用户 " + users.getUsername() + " 插入成功");
//            } else {
//                failCount++;
//                errorMsg.append("用户 ").append(users.getUsername()).append(" 插入失败; ");
//            }
//        } catch (Exception e) {
//            failCount++;
//            errorMsg.append("用户 ").append(users.getUsername()).append(" 插入异常: ").append(e.getMessage()).append("; ");
//        }
//    }
//    if (failCount > 0) {
//        return Result.success("导入完成，成功: " + successCount + "条，失败: " + failCount + "条。" + errorMsg.toString());
//    } else {
//        return Result.error( "导入完成，成功: " + successCount + "条，失败: " + failCount + "条。");
//    }
//}//文件导入优化
    @DeleteMapping("/user/batch/{ids}")
    public Result<?> deleteBatchUser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }

}
